from celery import shared_task
from django.utils import timezone
from hosts.models import HostPassword

@shared_task
def auto_change_host_passwords():
    # 获取所有需要修改密码的主机（下次修改时间 <= 当前时间）
    expired_passwords = HostPassword.objects.filter(next_change_time__lte=timezone.now())
    success_count = 0
    for host_password in expired_passwords:
        try:
            # 调用模型方法生成新密码并更新
            host_password.set_password(raw_password=None)  # 传None触发自动生成
            success_count += 1
        except Exception as e:
            # 记录失败日志（需配置日志系统）
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f'主机 {host_password.host.id} 密码自动修改失败: {str(e)}')
    return {
        'total': expired_passwords.count(),
        'success': success_count,
        'failed': expired_passwords.count() - success_count
    }